package org.ftc.util;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import net.sf.json.JSONArray;  
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;


public class Util {
	
	public static String injection(String str){
		if( str != null && str.length() > 0 ){
			int i = 0;
			StringBuffer tmp = new StringBuffer();
			for(char a : str.toCharArray()){
				if( i++ % 2 == 0){
					tmp.append('*');
				}else{
					tmp.append(a);
				}	
			}
			return tmp.toString();
		}
		return str;
	}
	
	public static String injection(String str, String chr){
		if( str != null && str.length() > 0 ){
			StringBuffer tmp = new StringBuffer();
			for(char a : str.toCharArray())
				tmp.append(chr + a); 	
			return (tmp.toString() + chr);
		}
		return str;
	}
	
	public static boolean isIntNumber(String num){
	    try{
	        Integer.parseInt(num);
	    } catch(NumberFormatException nfe) {
	        return false;
	    }
	    return true;
	}
	
	public static String shorten(String txt, Integer max){
		if( txt != null && txt.length() > max ){
			return txt.substring(0, max)+"..";
		}
		return txt;
	}
	
	public static String round(Double num, int digits){
		if( num == null ) return "0";
		 NumberFormat nf = NumberFormat.getInstance();
		 nf.setMaximumFractionDigits(digits); 
		 nf.setMinimumFractionDigits(digits); 
		 return nf.format(num);
	}
	
	public static String numUpperCase(int index){
		String[] serial = new String[]{"壹","貳","參","肆","伍","陸","柒","捌","玖","拾"}; 
		return serial[index];
	}
	
	public static String amtUpperCase(String amt){
		String [] cNum = {" 零 "," 壹 "," 貳 "," 參 "," 肆 "," 伍 "," 陸 "," 柒 "," 捌 "," 玖 "};
	    String [] cUnit = {"","拾","佰","仟","萬","拾萬","佰萬","仟萬","億","拾億"};
	    StringBuffer  str = new StringBuffer();
	    boolean naZero;
	    int index = amt.length();
        naZero = false;
        for( char a : amt.toCharArray() ){
        	index--;
            if( a > '0' ){
            	if( naZero ){
            		str.append(cNum[0]);
                    naZero = false;
            	}
                str.append(cNum[(int)(a-'0')]+cUnit[index]);
            } else{
            	naZero = true;
            }
            String b = cUnit[index <= 7 ? 4 : 8];
            int c = str.indexOf(b);
            int d = str.lastIndexOf(b);
            if( c == d ){
            	continue;
            }else{
            	str.deleteCharAt(c);
            }
        }
        if( str.length() == 0 )
        	str.append(cNum[0]);
        return str.toString();
    }
	
	
	public static String createPassWord(){
		int[] word = new int[8];
		char[] punctuation = new char[]{'!','@','#'};
		int mod;
		for(int i = 0; i < word.length; i++){
			mod = (int)(( Math.random() * 4));
			if(mod ==0){ //數字
				word[i]=(int)((Math.random()*10) + 48);
			}else if(mod ==1){ //大寫英文
				word[i] = (char)((Math.random()*26) + 65);
			}else if(mod ==2){ //小寫英文
				word[i] = (char)((Math.random()*26) + 97);
			}else{
				word[i] = punctuation[(int)(Math.random()*3)];
			} 
		}
		StringBuffer newPassword = new StringBuffer();
		for(int j = 0; j < word.length ; j++){
			newPassword.append((char)word[j]);
		}
		return newPassword.toString();
	}
	
	
	//bean 轉 json
	public static String beanToJson(Object object){
		if( object == null )
			return null;
		JsonConfig config = new JsonConfig();  
		JsonValueProcessor jsonValueProcessor = new JsonValueProcessor() {	
			public Object processObjectValue(String key, Object value, JsonConfig config) {
				if( value instanceof Date )
					return new SimpleDateFormat(Global.APP.DATE_FORMAT).format((Date) value);  
				return value;
			}
			public Object processArrayValue(Object value, JsonConfig config) {
				if( value instanceof Date )
					return new SimpleDateFormat(Global.APP.DATE_FORMAT).format((Date) value);  
				return value;
			}
		};
		config.registerJsonValueProcessor(Date.class, jsonValueProcessor );  
		JSONObject json = JSONObject.fromObject(object, config);
		return json.toString();
	}
	
	//陣列轉文字
	public static String listToString(List<String> array ) {
		StringBuilder arTostr = new StringBuilder();
	    if (array != null && array.size() > 0 ) {
	    	arTostr.append(array.get(0));
	    	for (int i = 1; i < array.size(); i++) {
	    		arTostr.append("¯" + array.get(i));
	        }
	    }
	    return arTostr.toString(); 
	}
			
	//文字轉陣列
	public static List<String> stringToList(String str ) {
		List<String> list = new ArrayList<String>();
	    if( str != null && str.length() > 0 ){   
	    	for(String s : str.split("¯")){
	    	   list.add(s);
	    	}
	    	return list;
	    }	
	    return list; 
	}
		
	//陣列轉文字
	public static String arrayToString(String[] array ) {
		StringBuilder arTostr = new StringBuilder();
	    if (array != null && array.length > 0 ) {
	    	arTostr.append(array[0]);
	    	for (int i = 1; i < array.length; i++) {
	    		arTostr.append("," + array[i]);
	        }
	    }
	    return arTostr.toString();
	}
		
	//文字轉陣列
	public static String[] stringToArray(String str ) {
        if( str != null && str.length() > 0 )
        	return str.split(",");
        return new String[0]; 
    }
		
	//list 轉 json
	public static String listToJson(List<HashMap<String, String>> list ) {
		if( list == null || list.size() <= 0 )
			return null;
		return JSONArray.fromObject(list).toString();
	}
	
	//json 轉  list
	public static List<HashMap<String, String>> jsonToList( String json ){
		if(json == null )
			return new ArrayList<HashMap<String, String>>();
		
		List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
		try{
			ObjectMapper mapper = new ObjectMapper();
			list = mapper.readValue(json, new TypeReference<List<HashMap<String, String>>>(){});
			return list;
		}catch (Exception e) {
			e.printStackTrace();
			return new ArrayList<HashMap<String, String>>();
		}
	}
	
	public static Integer yyyy(){
		Calendar cNow = Calendar.getInstance();
		return cNow.get(Calendar.YEAR);
	} 
	
	public static void main(String[] args) {

		System.out.println(Util.stringToList("s¯d¯f¯g¯h¯").size());
	}
	
	public static boolean isCutoff(Date date){
		if( date == null )
			return false;
		Calendar cutoff = Calendar.getInstance();
		cutoff.setTime(date);
		Calendar cal = Calendar.getInstance();//今天日期
		cal.add(Calendar.DAY_OF_WEEK, -1 );	//減一天
		return ( cal.compareTo(cutoff) >= 0 ); 
	}
	
	public static boolean isCutoff(Date start, Date end){
		boolean sb = true, eb = true;
		if( start != null ){
			Calendar scal = Calendar.getInstance();
			scal.setTime(start);
			sb = ( Calendar.getInstance().compareTo(scal) > 0 );
		}
		if( end != null ){
			Calendar ecal = Calendar.getInstance();
			ecal.setTime(end);
			ecal.add(Calendar.DAY_OF_WEEK, 1 );
			eb = ( Calendar.getInstance().compareTo(ecal) < 0 );
		}
		return !( sb && eb ); 
	}
}
